/**
 * Created by tanbingqin on 2020/11/6.
 */
import { messages } from "share/common";
import React from "react";
import { Icon, Button, Row, Col, message, Input, Popconfirm } from "antd";
import Condition from "components/condition";
const If = Condition.If;
import errorMessage from "share/errorMessage";
import subFormUtil from "components/template/sub-form/sub-form-util";
import SubFormRow from "components/template/sub-form/sub-form-row";
import "styles/components/template/sub-form/sub-form.scss";

class SubForm extends React.Component {
  state = {
    rowList: [],
    rowMax: 50, //可添加最大行数，默认值50
  };
  formRefObj = {}; //每个sub-form-row表单实例，key为`${frontOID}`
  changing = false;

  componentDidMount() {
    this.props.subFormRef && this.props.subFormRef(this);
    this.initRowList();
  }

  componentWillReceiveProps() {}

  shouldComponentUpdate(nextProps, nextState) {
    return this.changing;
  }

  componentDidUpdate() {
    this.changing = false;
  }

  initRowList = () => {
    const { field } = this.props;
    this.changing = true;
    this.setState(
      {
        rowList: subFormUtil.processRowList(field),
        rowMax: subFormUtil.processRowMax(field),
      },
      () => {
        this.props.onChange(JSON.stringify(this.state.rowList));
      }
    );
  };

  handleAddRow = () => {
    const { field } = this.props;
    let { rowList } = this.state;
    let newRow = subFormUtil.processTemplate(field);
    newRow.frontOID = subFormUtil.generateUid();
    rowList.push(newRow);
    this.setState({ rowList });
    this.changing = true;
    this.props.onChange(JSON.stringify(rowList));
  };

  handleDelete = (e, rowIndex) => {
    let { rowList } = this.state;
    rowList.splice(rowIndex, 1);
    this.setState({ rowList });
    this.changing = true;
    this.props.onChange(JSON.stringify(rowList));
  };

  handleRowChange = (formRefKey) => {
    let { rowList } = this.state;
    if (!formRefKey || !this.formRefObj[formRefKey]) {
      return;
    }
    this.changing = true;
    rowList.forEach((row, rowIndex) => {
      if (row.frontOID === formRefKey) {
        rowList[rowIndex] = this.formRefObj[formRefKey].getCustFormValues();
        rowList[rowIndex].frontOID = formRefKey;
      }
    });
    this.setState({ rowList });
    this.props.onChange(JSON.stringify(rowList));
  };

  //提供给父组件的调用方法 -- start --
  validateRow = () => {
    const { rowList } = this.state;
    let length = rowList.length;
    let i = 0;
    for (i; i < length; i++) {
      let refKey = rowList[i].frontOID;
      let res = this.formRefObj[refKey] ? this.formRefObj[refKey].validateItemsValue() : { validateResult: true }; //refKey找不到对应dom说明页面切换了，外层没有清空对应ref
      if (!res.validateResult) {
        //校验不通过
        this.changing = true;
        this.setState({ rowList }); //要重新触发下render使报错信息能够渲染上去
        return false;
      }
    }
    return true;
  };
  //提供给父组件的调用方法 -- end --

  render() {
    const { field } = this.props;
    const { rowList, rowMax } = this.state;
    return (
      <div className="sub-form-widget">
        {rowList.map((row, rowIndex) => {
          return (
            <div key={row.frontOID}>
              <Row type="flex" align="middle" className={`title-row ${rowIndex !== 0 ? "margin-top-32" : ""}`}>
                <Col span={20} className="font">
                  {field.fieldName}（{("0" + (rowIndex + 1)).substr(-2)}）
                </Col>
                <Col span={4} className="icon-block">
                  <If value={rowList.length > 1}>
                    <span className="icon-btn">
                      <Popconfirm
                        placement="topRight"
                        onConfirm={(e) => this.handleDelete(e, rowIndex)}
                        title={messages("request-1.key386") /*你确认要删除？*/}
                      >
                        <Icon type="delete" />
                      </Popconfirm>
                    </span>
                  </If>
                </Col>
              </Row>
              <SubFormRow
                field={field}
                fieldList={row}
                wrappedComponentRef={(form) => (this.formRefObj[`${row.frontOID}`] = form)}
                onChange={this.handleRowChange}
              />
            </div>
          );
        })}
        <If value={rowList.length < rowMax}>
          <Button onClick={this.handleAddRow} style={{ marginTop: 16 }}>
            <Icon type="plus" />
            {messages("common.add") /*添加*/}
          </Button>
        </If>
      </div>
    );
  }

  static propTypes = {
    field: React.PropTypes.object,
    onChange: React.PropTypes.func,
    subFormRef: React.PropTypes.func, // 获取子组件方法
  };

  static defaultProps = {
    field: {},
    onChange: () => {},
  };
}

export default SubForm;
